package com.study.designmodes.service.strategy.component;

import com.study.designmodes.request.BusinessObjectRequest;
import com.study.designmodes.service.strategy.StrategyService;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 策略模式bean工厂
 * <p>
 * StrategyServiceFactory 获取接口实现bean,并存储到 ConcurrentHashMap，通过枚举获取对应的实现bean
 *
 * @author yyb8152
 * @since 20220402
 **/
@Component
public class StrategyServiceFactory implements InitializingBean {


    /**
     * 注入ApplicationContext对象
     */
    @Autowired
    private ApplicationContext applicationContext;

    /**
     * 初始化存储策的map
     */
    private static final Map<BusinessObjectRequest, StrategyService> beans = new ConcurrentHashMap<>();

    /**
     * 从applicationContext 通过接口获取beans,并存储到 ConcurrentHashMap
     *
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        Map<String, StrategyService> strategyMap = applicationContext.getBeansOfType(StrategyService.class);
        if (MapUtils.isEmpty(strategyMap)) {
            return;
        }
        for (StrategyService value : strategyMap.values()) {
            BusinessObjectRequest businessObjectRequest = value.routeBusiness();
            if (!ObjectUtils.isEmpty(businessObjectRequest)) {
                beans.put(value.routeBusiness(), value);
            }

        }

    }
    //方法二：不用实现初始化bean的InitializingBean接口，但需要添加注解@Bean("operations")


    public static StrategyService getApiServiceByRequest(BusinessObjectRequest businessObjectRequest) {
        StrategyService strategyService = beans.get(businessObjectRequest);
        if (ObjectUtils.isEmpty(strategyService)) {
            throw new RuntimeException("路由参数不正确或为空！");
        }
        return strategyService;


    }
}
